package com.mall.web.controller.wechat;

import com.mall.common.core.controller.BaseController;
import com.mall.common.core.domain.AjaxResult;
import com.mall.common.core.domain.entity.SysUser;
import com.mall.framework.web.service.SysLoginService;
import com.mall.wechat.model.Vo.WxCodeVo;
import com.mall.wechat.model.Vo.WxLoginVo;
import com.mall.wechat.model.dto.WxLoginDto;
import com.mall.wechat.service.IWeChatLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/mini/weChat")
@Api(value = "//mini/weChat", description = "用户端微信小程序相关Controller")
public class WeChatLoginController extends BaseController  {

    @Resource
    private SysLoginService loginService;

    @Resource
    private IWeChatLoginService weChatLoginService;

    @GetMapping("/getWxCode")
    @ResponseBody
    @ApiOperation(value = "获取微信用户code信息", httpMethod = "GET")
    public AjaxResult getCodeInfo(@RequestParam (value = "code", required = true) String code,
                                             @RequestParam (value = "wxAppId", required = true) String wxAppId) {
        WxCodeVo wxCodeVo = weChatLoginService.getWxCode(wxAppId, code);
        return success(wxCodeVo);
    }

    @PostMapping("wxLogin")
    @ResponseBody
    @ApiOperation(value = "微信登录", httpMethod = "POST")
    public AjaxResult wxLogin(@RequestBody WxLoginDto wxLoginDto){
        String phoneNumber = weChatLoginService.gerPhoneNumber(wxLoginDto);
        String openid = wxLoginDto.getOpenid();
        String unionId = wxLoginDto.getUnionId();
        String wxAppId = wxLoginDto.getWxAppId();
        WxLoginVo wxLoginVo
                = weChatLoginService.wxLogin(phoneNumber, openid, unionId, wxAppId);
        wxLoginVo.setPhone(phoneNumber);
        SysUser user = wxLoginVo.getSysUser();
        String token = loginService.login(user.getUserName(), user.getPassword(), null, null);
        wxLoginVo.setToken(token);
        return success(wxLoginVo);
    }
}

